package wfm.ws.addressValidation.rest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import com.util.geolocation.LocationAPI;
import com.util.geolocation.MyGeoPoint;

import wfm.entities.Address;
import wfm.entities.Customer;

public class AddressValidationRESTServiceImpl implements AddressValidationRESTService
{
	private List<Address> knownAddresses = new ArrayList<Address>();
	
	public AddressValidationRESTServiceImpl()
	{
		this.knownAddresses.add(new Address("Teststraße 1", "Wien", "1010", "Austria"));
		this.knownAddresses.add(new Address("Karlsplatz 13", "Wien", "1040", "Austria"));
		this.knownAddresses.add(new Address("Karlsplatz", "Wien", "1040", "Austria"));
		this.knownAddresses.add(new Address("Getreidegasse 34", "Salzburg", "5020", "Austria"));
		this.knownAddresses.add(new Address("Bürgergasse 14", "Graz", "8010", "Austria"));
		this.knownAddresses.add(new Address("Behrenstraße 37", "Berlin", "10117", "Germany"));
	}
	
	@Override
	public Address validateAddress(String street, String city, String zip, String country)
	 throws WebApplicationException
	{				
		Address address = new Address(street,city,zip,country);
		try {
			MyGeoPoint gp=LocationAPI.getLocation(address.toString());
			if(gp != null){
				String add=LocationAPI.getAdress(gp);
				if(add!=null && add.contains(street) && add.contains(city) && add.contains(zip) && add.contains(country))
					return address;
			}
			
		} catch (Exception e) {
			return null;
		}
		
		return null;
//		ResponseBuilder builder = Response.status(Status.NOT_FOUND);
//		builder.type("text/html");
//		builder.entity("<h3>Invalid address! Address could not be found</h3>");
//
//		throw new WebApplicationException(builder.build());
	}
	
	@Override
	public Object isValidAddress(String firstName, String lastName,
			String street, String city, String zip, String country,
			String telNo, String mailAddress)
	 throws WebApplicationException
	{	
		if(zip.length() == 4 && zip.matches("[0-9]*")) {
			return Boolean.TRUE;
		}
		
		ResponseBuilder builder = Response.status(Status.NOT_FOUND);
		builder.type("text/html");
		builder.entity("<h3>Invalid address! Zip code is not valid</h3>");

		throw new WebApplicationException(builder.build());
	}
}
